<template>
    <role-dialog class="ruleForm" :title="props.title" :show="props.show" @close="close" @submit="submit">
        <el-form :model="roleData" :rules="rules" ref="roleForm" label-width="100">
            <el-form-item label="角色名称" prop="roleName">
                <el-input v-model="roleData.roleName" placeholder="请输入角色名称"></el-input>
            </el-form-item>
            <el-form-item label="备注" prop="remark">
                <el-input :rows="2" type="textarea" v-model="roleData.remark" placeholder="请输入备注"></el-input>
            </el-form-item>
        </el-form>
    </role-dialog>
</template>

<script setup lang='ts'>
import { ref, reactive, watch, computed, PropType, nextTick } from 'vue'
import roleDialog from "@/components/Dialog.vue"
import type { FormInstance, FormRules } from "element-plus"
import { RoleRow } from "@/interface/role"

const props = defineProps({
    show: {
        type: Boolean,
        default: true,
        required: true
    },
    title: {
        type: String,
        default: '新增菜单',
        required: true
    },
    roleFormData: Object as PropType<RoleRow>,
    type: String
})
let roleData = ref<RoleRow>({
    roleName: '',
    remark: ''
})

// 监听是新增还是编辑
watch(() => props.type, (newValue, oldValue) => {
    let action = newValue ? newValue : 'add'
    console.log(action)
    if (action === 'edit') {
        nextTick(() => {
            roleData.value = props.roleFormData as RoleRow
        })
    }
}, { immediate: true })

// 表单设置
const roleForm = ref<FormInstance>()
const rules = reactive<FormRules>({
    roleName: [{ required: true, message: '请输入角色名称', trigger: 'blur' }],
})

const emits = defineEmits(["close", "submit"])
const close = () => {
    roleForm.value?.resetFields()
    emits("close")
}
const submit = () => {
    roleForm.value?.validate((valid: boolean) => {
        if (valid) {
            const params = Object.assign({}, roleData.value)
            emits("submit", params)
            setTimeout(() => {
                close()
            }, 0)
        }
    })
}
</script>
<style lang='scss' scoped>
.el-dialog__header {
    border-bottom: 1px solid red;
}
</style>